﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _7
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      if (graphics == null)
        graphics = this.CreateGraphics();
      else
        graphics.Clear(this.BackColor);
      if (updateParameters())
      {
        drawCayleyTree(n, 170, 310, leng, -Math.PI / 2);
      }
    }

    private bool updateParameters()
    {
      this.n= int.Parse(textBox1.Text);//范围1-15,测试过20会出错
      this.leng = double.Parse(textBox2.Text);
      this.th1 = double.Parse(textBox5.Text)* Math.PI / 180;
      this.th2 = double.Parse(textBox6.Text)* Math.PI / 180;
      this.per1 = double.Parse(textBox3.Text);
      this.per2 = double.Parse(textBox4.Text);
      TextBox[] textBoxes = { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6 };
      foreach (TextBox textBox in textBoxes)
      {
        // 检查 TextBox 内容是否为空或空白
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
          MessageBox.Show("请输入有效值！");
          return false;
        }
      }

      if (n <= 0 || n > 15 || per1 <= 0 || per2 <= 0)
      {
        MessageBox.Show("参数错误，建议使用推荐参数");
        return false;
      }

      return true;
    }

    private Graphics graphics;
    private int n = 10;
    private double leng = 100;
    private double per1 = 0.6;
    private double per2 = 0.7;
    private double th1 = 30 * Math.PI / 180;
    private double th2 = 20 * Math.PI / 180;
    private Color penColor = Color.Blue;
    

    void drawCayleyTree(int n, double x0, double y0, double leng, double th)
    {
      
      //不合法的数据
      if (n == 0)
      {
        return;
      }
      double x1 = x0 + leng * Math.Cos(th);
      double y1 = y0 + leng * Math.Sin(th);
      drawLine(x0, y0, x1, y1);
      drawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1);
      drawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2);
    }

    void drawLine(double x0, double y0, double x1, double y1)
    {
      using (Pen pen = new Pen(penColor))
      {
        graphics.DrawLine(pen, (int)x0, (int)y0, (int)x1, (int)y1);
      }
    }

    private void btnColor_Click(object sender, EventArgs e)
    {
      ColorDialog colorDialog = new ColorDialog();
      if (colorDialog.ShowDialog() == DialogResult.OK)
      {
        penColor = colorDialog.Color;
      }
    }
  }
}
